<?php

namespace app\admin\model;

use think\Model;

class Menu extends Model
{
    protected $autoWriteTimestamp = 'datetime';

    public static function getMenuNameById($id = 0)
    {
        return self::where('id',$id)->value('name');
    }

    public static function getCurrentMenu($currentMenu)
    {
        $currMenu = self::where('permission_key','menu-'.$currentMenu)->find();
        return $currMenu;
    }

    /**
     * 网站标题
     */
    public static  function getMetaTitle($currentMenu)
    {
    	if (!cache($currentMenu.'-currentMenu')) {
    		$curr = self::where('permission_key','menu-'.$currentMenu)->value('name');
    		cache($currentMenu.'-currentMenu',$curr);
    		return $curr;
    	}
    	return cache($currentMenu.'-currentMenu');
	}
    /**
     * 面包屑导航（当前显示菜单）
     * @param  当前路由 (不带前缀)
     */
    public static function getBreadcrumb($currentMenu)
    {
        if (!cache('b-'.$currentMenu)) {
            $pId = self::where('permission_key','menu-'.$currentMenu)->value('parent_id');
            $menus = self::find($pId);
            if (!$menus) {
                $bm = '<li class="active"><strong>'.self::getMetaTitle($currentMenu).'</strong></li>';
                cache('b-'.$currentMenu,$bm);
                return $bm;
            }
            $bm = '<li>'.$menus['name'].'</li><li class="active"><strong>'.self::getMetaTitle($currentMenu).'</strong></li>';
            cache('b-'.$currentMenu,$bm);
            return $bm;
        }

        return cache('b-'.$currentMenu);
    }

    public static function getHtmlMenu(){
        $menus = self::where(['status' => 1])->order('weight','desc')->select()->toArray();
        $data = self::getTreeMenu($menus);
        return $data;
    }

    protected static function getTreeMenu($data){
        $items = array();
        foreach($data as $v){
            $items[$v['id']] = $v;
        }
        $tree = array();
        foreach($items as $k => $item){
            if(isset($items[$item['parent_id']])){
                $items[$item['parent_id']]['son'][] = &$items[$k];
            }else{
                $tree[] = &$items[$k];
            }
        }
        return $tree;
    }
}
